/*
** map.c for map in /home/gjura_r//SDL/projet
** 
** Made by romain gjura
** Login   <gjura_r@epitech.net>
** 
** Started on  Fri Apr 12 11:44:08 2013 romain gjura
** Last update Tue Apr 16 10:20:55 2013 romain gjura
*/

#define  _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include "./includes/map.h"

void		fill_tab(char *line, int *tab, int nb)
{
  int		i = 0;

  while (i < nb)
    {
      tab[i] = line[i] - 48;
      i++;
    }
}

int		read_map(FILE *fd, t_map *map)
{
  char		*line = NULL;
  size_t	len = 0;
  ssize_t	read = 0;
  int		i = 0;

  if ((map->tab = malloc(sizeof(int*) * map->nb_line)) == NULL)
    {
      fprintf(stderr, "Error: malloc\n");
      return EXIT_FAILURE;
    }
  while ((read = getline(&line, &len, fd)) != -1)
    {
      line[read - 1] = '\0';
      if ((map->tab[i] = malloc(sizeof(int) * map->nb_col)) == NULL)
	{
	  fprintf(stderr, "Error: malloc\n");
	  return EXIT_FAILURE;
	}
      fill_tab(line, map->tab[i], map->nb_col);
      i++;
    }
  free(line);
  return EXIT_SUCCESS;
}

int		count(FILE *fd, t_map *map)
{
  char		*line = NULL;
  size_t	len = 0;
  ssize_t	read = 0;
  static int	test;  

  map->nb_line = 0;
  map->nb_col = 0;
  while ((read = getline(&line, &len, fd)) != -1)
    {
      line[read - 1] = '\0';
      if (test > 0)
      	if ((read - 1) != map->nb_col)
      	  {
      	    fprintf(stderr, "Map error: columns must have the same number of numb\n");
      	    return EXIT_FAILURE;
      	  }
      map->nb_col = (read - 1);
      map->nb_line++;
      test++;
    }
  free(line);
  return EXIT_SUCCESS;
}

void		free_tab(int **tab, int nb)
{
  int		i = 0;

  while (i < nb)
    {
      free(tab[i]);
      i++;
    }
  free(tab);
}

int		alloc_copy(t_map *map)
{
  int		i = 0;

  if ((map->copy = malloc(sizeof(int*) * map->nb_line)) == NULL)
    {
      fprintf(stderr, "Error: malloc\n");
      return EXIT_FAILURE;
    }
  while (i < map->nb_line)
    {
      if ((map->copy[i] = malloc(sizeof(int) * map->nb_col)) == NULL)
	{
	  fprintf(stderr, "Error: malloc\n");
	  return EXIT_FAILURE;
	}
      i++;
    }
  return EXIT_SUCCESS;
}

/* old & new MUST have the same size */
int		**copy_tab(int **old, int **new, t_map *map)
{
  int		i = 0, i2 = 0;

  while (i2 < map->nb_line)
    {
      i = 0;
      while (i < map->nb_col)
	{
	  new[i2][i] = old[i2][i];
	  i++;
	}
      i2++;
    }
  return new;
}
